package com.greet.service.impl;

import com.greet.entity.Category;
import com.greet.entity.Dish;
import com.greet.entity.DishFlavor;
import com.greet.mapper.CategoryMapper;
import com.greet.mapper.DishFlavorMapper;
import com.greet.mapper.DishMapper;
import com.greet.service.DishViewService;
import com.greet.utils.PojoTypeTranformationUtil;
import com.greet.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishViewServiceImpl implements DishViewService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<DishVO> getDishes(Long categoryId) {
        //查询redis中是否存在想要的数据，如果有直接返回，没有就查询并把数据存入Redis
        //构造key, 规则：dish_分类id
        String key = "dish_" + categoryId;

        //查询redis中是否存在
        List<DishVO> obj = (List<DishVO>)redisTemplate.opsForValue().get(key);
        if (obj != null && obj.size() > 0){
            return obj;
        }

        List<Dish>  dishList = dishMapper.select(Dish.builder().categoryId(categoryId).status(1).build());
        List<DishVO> dishVOList = new ArrayList<>(15);
        for (Dish dish : dishList){
            DishVO dishVO = PojoTypeTranformationUtil.toDishVO(dish);
            dishVO.setFlavors(
                    dishFlavorMapper.select(
                            DishFlavor.builder().dishId(dish.getId()).build()
                    )
            );
            dishVO.setCategoryName(
                    categoryMapper.select(
                            Category.builder().id(dish.getCategoryId()).build()
                    ).get(0).getName()
            );
            dishVOList.add(dishVO);
        }
        //把缓存数据存入Redis
        redisTemplate.opsForValue().set(key, dishVOList);
        return dishVOList;
    }
}
